/**
 * Description:
 * Class Name:ReadFile
 * Date:2022/5/3 18:32
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第15章_输入输出._15_9_NIO._15_9_3_使用Channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        String path = "./src/" + ReadFile.class.getName().replace(".", "/") + ".java";
        try (
                var fis = new FileInputStream(path);
                FileChannel fileChannel = fis.getChannel();
                var fos = new FileOutputStream("Chapter_15_9_3_输出测试.txt");
                FileChannel fileChannel2 = fos.getChannel()
                ){
            // 既然要创建循环读取的容器，就要涉及到ByteBuffer
            ByteBuffer buffer = ByteBuffer.allocate(256);
            // Channel只能跟Buffer交互
            while ((fileChannel.read(buffer)) > 0){
                // 注意Buffer的几个重要用法：flip和clear
                // 首先flip()准备数据
                buffer.flip();
                // 处理数据
                fileChannel2.write(buffer);
                // 恢复position和limit
                buffer.clear();
            }
        }
    }
}
